

//
//  ConsignmentOrRecyclingDetailVC.m
//  LuxuryGoods
//
//  Created by DCQ on 2018/8/6.
//  Copyright © 2018年 Future. All rights reserved.
//

#import "ConsignmentOrRecyclingDetailVC.h"
#import "LGImageManagerIO.h"
#import "UserInfoModel.h"
#import "ConOrReDetailModel.h"
#import "OrderDetailNotifierCell.h"
#import "GoodsSectionCell.h"
#import "ConOrReDetailGoodsInfoCell.h"
#import "ConOrReDetailGoodsSellCell.h"
#import "OrderAddressCell.h"
#import "OrderGoodsServiceCell.h"
#import "OrderInfoCell.h"
#import "AddSendInfoViewController.h"
#import "OrderLogisticsViewController.h"
#import "UrgentMoneyView.h"
#import "AdjustPriceViewController.h"
#import "CustomerServiceViewController.h"

NSString * const ConOrReNotifierCellIdentifier = @"ConOrReNotifierCellIdentifier";
NSString * const ConOrReGoodsSectionCellIdentifier = @"ConOrReGoodsSectionCellIdentifier";
NSString * const ConOrReDetailGoodsInfoCellIdentifier = @"ConOrReDetailGoodsInfoCellIdentifier";
NSString * const ConOrReDetailGoodsSellCellIdentifier = @"ConOrReDetailGoodsSellCellIdentifier";
NSString * const ConOrReAddressCellIdentifier = @"ConOrReAddressCellIdentifier";
NSString * const ConOrReGoodsServiceCellIdentifier = @"ConOrReGoodsServiceCellIdentifier";
NSString * const ConOrReInfoCellIdentifier = @"ConOrReInfoCellIdentifier";



@interface ConsignmentOrRecyclingDetailVC ()
@property(nonatomic, assign) ConsignmentOrRecyclingDetailState state;
@property(nonatomic, assign) ConsignmentOrRecyclingDetailType type;
@property(nonatomic, copy) NSString * orderId;
@property(nonatomic, strong)  ConOrReDetailModel  *detailModel;
@property(nonatomic, strong) UrgentMoneyView * urgentView;
@property(nonatomic, strong)   ConOrReGoodsModel *selectedGoodsModel;
@end

@implementation ConsignmentOrRecyclingDetailVC
- (instancetype)initWithStyle:(ConsignmentOrRecyclingDetailState)state withVCType:(ConsignmentOrRecyclingDetailType)type withOrderId:(NSString *)order_id{
    self = [super init];
    if (self) {
        self.state = state;
        self.type = type;
        self.orderId = order_id;
    }
    return self;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString * titleStr = [self getTitleWithStyle:self.state];
    [self setNavigationItemTitle: titleStr];
    [self requestOrderDetail];
    if (self.state == ConsignmentOrRecyclingDetailState_completeOffer) {
        [self setupBottomView];
    }
}
- (NSString *)getTitleWithStyle:(NSInteger )style{
    NSString * stateStr = @"";
    //订单状态  0-待报价 10-已报价 20-已寄件 30-出售中(寄卖专用) 40-已完成 90-已取消
    switch (style) {
        case 0:
            stateStr = @"待报价";
            
            break;
        case 10:
            stateStr = @"已报价";
            
            break;
  
            
        case 20:
            stateStr = @"已寄件";
            
            break;
        case 30:
            stateStr = @"出售中";
            
            break;
        case 40:
            stateStr = @"已完成";
            
            break;
       
        case 90:
            stateStr = @"取消";
            
            break;
        default:
            break;
    }
    return stateStr;
}

#pragma mark ---
- (void)setupBottomView{
    CGFloat bottomHeight = 50;
    UIView * bottomView = [[UIView alloc]initWithFrame:CGRectMake(0,  self.view.frame.size.height-bottomHeight, self.view.frame.size.width, bottomHeight)];
    [bottomView setBackgroundColor:[UIColor whiteColor]];
    [self.view addSubview:bottomView];
    NSString * btnTitle = @" ";
    btnTitle = @"填写寄件物流";
    UIButton * btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setTitle:btnTitle forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    
    [btn addTarget:self action:@selector(btAction:) forControlEvents:UIControlEventTouchUpInside];
    [btn setFrame:CGRectMake(20, 5, self.view.frame.size.width -40, bottomHeight- 10)];
    btn.layer.cornerRadius = (bottomHeight- 10)/2;
    btn.layer.masksToBounds =  YES;
    btn.titleLabel.font = [UIFont systemFontOfSize:14];
    [bottomView addSubview:btn];
    UIImage * bgImg = [LGImageManagerIO createGradualColorImage:btn.size startColor:UIColorFromRGB(0xE1CFA9) endColor:UIColorFromRGB(0xC1B284)];
    [btn setBackgroundImage:bgImg forState:UIControlStateNormal];
}

- (void)btAction:(id)sender{
     //填写寄件物流
    [self  gotoAddExpressVC];
    
}
- (void)setupRightItem{
    
    NSString * barTitle = @"";
    if (self.state == ConsignmentOrRecyclingDetailState_waitOffer ||self.state == ConsignmentOrRecyclingDetailState_completeOffer ) {
        barTitle  =@"取消订单";
    }
    UIButton * rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [rightBtn setTitle:barTitle forState:UIControlStateNormal];
    [rightBtn setTitleColor:UIColorFromRGB(0x333333) forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(rightAction:) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];
    self.navigationItem.rightBarButtonItem = rightItem;
}

- (void)rightAction:(id)sender{
  
        //        barTitle  =@"取消订单";
        [self showAlertView:@"确定取消该订单吗?" withConfirmAction:^(UIAlertAction *action) {
            [self requestCancelOrder];
        } withCancelAction:^(UIAlertAction *action) {
        }];
    
}
- (void)requestCancelOrder{
    NSDictionary * params = @{@"order_id":self.orderId,@"token":UserInfo.userToken};
    
    [[MainApi sharedInstance] postPath:@"/Consignorder/cancelOrder" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        
        NSLog(@"%@===",responseObject);
        if (!error) {
            NSString * notificationName = @"";
            if (self.fromVCType == ConsignmentOrRecyclingFromVCType_Msg) {
                notificationName = @"UPDATE_MESSAGE_LIST";
            }else{
                notificationName = @"UPDATE_ConOrReOrder_LIST";
            }
            [[NSNotificationCenter defaultCenter] postNotificationName:notificationName object:nil];
            [self backViewController];
        }
        
        
    }];
}
#pragma mark -====

- (void)requestOrderDetail{
    NSDictionary * params = @{@"order_id":self.orderId,@"token":UserInfo.userToken};
    WEAKSELF
    [[MainApi sharedInstance] postPath:@"Consignorder/detail" params:params resultBlock:^(NSDictionary *responseObject, NSError *error) {
        STRONGSELF
        NSLog(@"%@===",responseObject);
        if (responseObject && !error) {
            strongSelf.detailModel = [[ConOrReDetailModel alloc]initWithDictionary:responseObject error:nil];
        }
         [self setNavigationItemTitle: [strongSelf getTitleWithStyle:[strongSelf.detailModel.data.status integerValue]]];
        [strongSelf.tableView reloadData];
    }];
}

#pragma mark ---
- (void)registerCell{
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderAddressCell class]) bundle:nil] forCellReuseIdentifier:ConOrReAddressCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderDetailNotifierCell class]) bundle:nil] forCellReuseIdentifier:ConOrReNotifierCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ConOrReDetailGoodsSellCell  class]) bundle:nil] forCellReuseIdentifier:ConOrReDetailGoodsSellCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([ConOrReDetailGoodsInfoCell class]) bundle:nil] forCellReuseIdentifier:ConOrReDetailGoodsInfoCellIdentifier];
    
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderGoodsServiceCell  class]) bundle:nil] forCellReuseIdentifier:ConOrReGoodsServiceCellIdentifier];
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([OrderInfoCell  class]) bundle:nil] forCellReuseIdentifier:ConOrReInfoCellIdentifier];
   
  
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([GoodsSectionCell   class]) bundle:nil] forCellReuseIdentifier:ConOrReGoodsSectionCellIdentifier];
    
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    NSInteger section =  0;
    if (self.detailModel) {
        section = 5;
    }
    return section;
}
- (CGRect)getTableViewFrame{
    
    CGFloat bottomHeight = 0;
    if (self.state == ConsignmentOrRecyclingDetailState_completeOffer) {
         bottomHeight = 50;
    }
    CGRect tableFrame = CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height -bottomHeight);
    return tableFrame;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    NSInteger row = 0;
    switch (section) {
        case 0:{
            if(self.state == ConsignmentOrRecyclingDetailState_completeGoods || (self.type == ConsignmentOrRecyclingDetailType_Re && self.state == ConsignmentOrRecyclingDetailState_complete)){
                row = 1;
                
            }else{
                row = 0;
            }
        }
            break;
   
        case 1:
            row = [self.detailModel.data.goods_item count]+1;
            break;
        case 2:
            if (self.state == ConsignmentOrRecyclingDetailState_waitOffer  ||(self.state == ConsignmentOrRecyclingDetailState_cancel && self.type== ConsignmentOrRecyclingDetailType_Con)) {
                row = 0;
            }else if ((self.state == ConsignmentOrRecyclingDetailState_completeOffer||self.state == ConsignmentOrRecyclingDetailState_complete||self.state == ConsignmentOrRecyclingDetailState_completeGoods) && self.type== ConsignmentOrRecyclingDetailType_Con) {
                row = 1;
                
            }else if (self.type== ConsignmentOrRecyclingDetailType_Re && (self.state != ConsignmentOrRecyclingDetailState_waitOffer)){
                row = 1;
            }
            break;
        case 3:
           
            //寄卖 且不是带报价状态
            if (self.type== ConsignmentOrRecyclingDetailType_Re && (self.state != ConsignmentOrRecyclingDetailState_waitOffer)){
                row = 1;
            }
            break;
        case 4:
            row =    2;
            break;
            
        default:
            break;
    }
    
    return row;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if (indexPath.section == 0) {
        OrderDetailNotifierCell * tempCell = [tableView dequeueReusableCellWithIdentifier: ConOrReNotifierCellIdentifier];
        DetailNotifierStyle style =  DetailNotifierStyle_noraml;
        NSString * logisticsName = @"";
        NSString * logisticsNo = @"";
        style = DetailNotifierStyle_logistics;
        logisticsName = self.detailModel.data.express_name;
        logisticsNo = self.detailModel.data.express_no;
        [tempCell  setupOrderDetail:style withLogisticsName:logisticsName withLogisticsNo:logisticsNo];
        tempCell.btnBlock = ^(DetailNotifierStyle style) {
            if (style == DetailNotifierStyle_logistics) {
                //物流
                [self gotoLogisticsVC];
            }
        };
        cell = tempCell;
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            GoodsSectionCell * tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReGoodsSectionCellIdentifier];
            NSString * titleStr = @"";
            if (self.type == ConsignmentOrRecyclingDetailType_Con) {
                titleStr = @"寄卖商品";
            }else if (self.type == ConsignmentOrRecyclingDetailType_Re){
                titleStr = @"回收商品";
            }
            [tempCell setupTitle:titleStr];
            cell = tempCell;
        }else{
            
            if (self.state == ConsignmentOrRecyclingDetailState_waitOffer
                ||self.state == ConsignmentOrRecyclingDetailState_completeOffer
                || self.state == ConsignmentOrRecyclingDetailState_completeGoods
                || self.state == ConsignmentOrRecyclingDetailState_cancel) {
               
                ConOrReDetailGoodsInfoCell *tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReDetailGoodsInfoCellIdentifier];
                [tempCell setupGoodsInfo: self.detailModel.data.goods_item[indexPath.row -1]];
                [tempCell  showSalePrice:NO];
                cell = tempCell;
            }else if (self.type == ConsignmentOrRecyclingDetailType_Re && self.state == ConsignmentOrRecyclingDetailState_complete){
                ConOrReDetailGoodsInfoCell *tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReDetailGoodsInfoCellIdentifier];
                [tempCell setupGoodsInfo:self.detailModel.data.goods_item[indexPath.row -1]];
                //回收价
                [tempCell  showSalePrice:YES];
                cell = tempCell;
                
            }else if (self.state == ConsignmentOrRecyclingDetailState_sell && self.type == ConsignmentOrRecyclingDetailType_Con){
     
                ConOrReDetailGoodsSellCell *tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReDetailGoodsSellCellIdentifier];
                [tempCell setupGoodsInfo:self.detailModel.data.goods_item[indexPath.row -1]];
                tempCell.btnBlock = ^(NSIndexPath *indexPath) {
                   ConOrReGoodsModel * goodsModel = self.detailModel.data.goods_item[indexPath.row -1];
                    [self showUrgentView:goodsModel];
                };
                cell = tempCell;
            }else if (self.state == ConsignmentOrRecyclingDetailState_complete && self.type == ConsignmentOrRecyclingDetailType_Con){
                ConOrReDetailGoodsSellCell *tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReDetailGoodsSellCellIdentifier];
                [tempCell setupGoodsInfo:self.detailModel.data.goods_item[indexPath.row -1]];
                cell = tempCell;
                
            }
            
        }
    
    }else if (indexPath.section == 2){
        OrderAddressCell * tempCell = [tableView dequeueReusableCellWithIdentifier: ConOrReAddressCellIdentifier];
        [tempCell setupSendAddressInfo:self.detailModel.data withTitle:@"寄件地址"];
        cell = tempCell;
    }else if (indexPath.section == 3){
        OrderAddressCell * tempCell = [tableView dequeueReusableCellWithIdentifier: ConOrReAddressCellIdentifier];
        [tempCell setupBackAddressInfo:self.detailModel.data withTitle:@"回寄地址"];
        cell = tempCell;
        
    }else if (indexPath.section == 4){
        if (indexPath.row ==  0){
            OrderGoodsServiceCell * tempCell = [tableView dequeueReusableCellWithIdentifier:ConOrReGoodsServiceCellIdentifier];
            tempCell.serviceBlock = ^{
            //联系客服
                [self gotoServiceVC];
            };
            cell = tempCell;
        }else if (indexPath.row ==  1){
            OrderInfoCell * tempCell =[tableView dequeueReusableCellWithIdentifier:ConOrReInfoCellIdentifier];
            [tempCell setupADdressData:self.detailModel.data  withState:self.navigationItem.title];
            cell = tempCell;
        }
    }
    return cell;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    CGFloat height = 0;
    if (indexPath.section == 0) {
        height = 114;
        
    }else if (indexPath.section == 1){
        if (indexPath.row == 0) {
            height = 30;
        }else{
            height = 95;
            
        }
        
    }else if (indexPath.section == 2){
        height = 100;
        
    }else if (indexPath.section == 3){
        height = 100;
        
    }else if (indexPath.section == 4){
         if (indexPath.row ==    0){
            height = 76;
        }else if (indexPath.row ==   1){
            height = 80;
        }
        
    }
    
    return height;
}


- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    CGFloat height = 0.001;
    switch (section) {
        case 0:{
            if(self.state == ConsignmentOrRecyclingDetailState_completeGoods || (self.type == ConsignmentOrRecyclingDetailType_Re && self.state == ConsignmentOrRecyclingDetailState_complete)){
                height = 10;
                
            }else{
                height = 0;
            }
        }
            break;
            
        case 1:
            height = 10;
            break;
        case 2:
            if (self.state == ConsignmentOrRecyclingDetailState_waitOffer  ||(self.state == ConsignmentOrRecyclingDetailState_cancel && self.type== ConsignmentOrRecyclingDetailType_Con)) {
                height = 0;
            }else if ((self.state == ConsignmentOrRecyclingDetailState_completeOffer||self.state == ConsignmentOrRecyclingDetailState_complete||self.state == ConsignmentOrRecyclingDetailState_completeGoods) && self.type== ConsignmentOrRecyclingDetailType_Con) {
                height = 10;
                
            }else if (self.type== ConsignmentOrRecyclingDetailType_Re && (self.state != ConsignmentOrRecyclingDetailState_waitOffer)){
                height = 10;
            }
            break;
        case 3:
            
            //寄卖 且不是带报价状态
            if (self.type== ConsignmentOrRecyclingDetailType_Re && (self.state != ConsignmentOrRecyclingDetailState_waitOffer)){
                height = 10;
            }
            break;
        case 4:
            height =  10;
            break;
            
        default:
            break;
    }
    return height;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.section == 0) {
        //物流
        [self gotoLogisticsVC];
    }else if (indexPath.section == 1){
        ConOrReGoodsModel * model = self.detailModel.data.goods_item[indexPath.row -1];
        if ([model.goods_status integerValue] == 10) {
            [self gotoSingleGoodsLogisticeVC:[NSString stringWithFormat:@"%@",model.order_goods_id]];
        }
        
    }
    
    
}
#pragma mark ---
- (void)gotoSingleGoodsLogisticeVC:(NSString *) goodsId{
    
    OrderLogisticsViewController * logisticsVC = [[OrderLogisticsViewController alloc]initOrderId:self.orderId withVCType:LogisticsVCType_conOrReSingle withGoodsId:goodsId];
    [self pushViewController:logisticsVC];
    
}
- (void)gotoLogisticsVC{
    OrderLogisticsViewController * logisticsVC = [[OrderLogisticsViewController alloc]initOrderId:self.orderId withVCType:LogisticsVCType_idOrMatn];
    [self pushViewController:logisticsVC];
    
}

-  (void)gotoAddExpressVC{
    AddSendInfoViewController * sendInfoVC = [[AddSendInfoViewController alloc]initWithOrderId:self.orderId withType:AddSendInfoVCType_conOrRe];
    if (self.fromVCType == ConsignmentOrRecyclingFromVCType_Msg) {
        sendInfoVC.fromVCType = AddSendInfoFromVCType_Msg;
    }
   
    [self pushViewController:sendInfoVC];
    
}

- (void)showUrgentView:(ConOrReGoodsModel *)model{
    self.selectedGoodsModel = model;
    WEAKSELF
    self.urgentView.btnAction = ^(UrgentMoneyBtnType type) {
           [weakSelf.urgentView removeFromSuperview];
        if (type == UrgentMoneyBtnType_close) {
  
        }else if (type == UrgentMoneyBtnType_tiaojiao){
            
              [weakSelf gotoTiaoJiaoVC ];
        }
        else if (type == UrgentMoneyBtnType_huishou){
            
              [weakSelf gotoHuiShou];
        }
        else if (type == UrgentMoneyBtnType_bumaile){
            [weakSelf gotoBuMaiLe];
            
        }
  
    };
    [self.view addSubview:self.urgentView];
    
}

- (UrgentMoneyView *)urgentView{
    if (!_urgentView) {
        _urgentView = [[NSBundle mainBundle] loadNibNamed:NSStringFromClass([UrgentMoneyView class]) owner:nil options:nil].firstObject;
    }
    return _urgentView;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//客服
- (void)gotoServiceVC{
    CustomerServiceViewController * tempVC = [[CustomerServiceViewController alloc]init];
    [self pushViewController:tempVC];
    
}
- (void)gotoTiaoJiaoVC{
    AdjustPriceViewController * vc = [[AdjustPriceViewController alloc]initWithModel:self.selectedGoodsModel];
 
    if (self.fromVCType == ConsignmentOrRecyclingFromVCType_Msg) {
        vc.fromVCType = AdjustPriceViewFromVCType_Msg;
    }
    [self pushViewController:vc];
    
}
- (void)gotoHuiShou{
    
    [self  gotoServiceVC];
}

- (void)gotoBuMaiLe{
     [self  gotoServiceVC];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
